<?php
class Language {

    public function __construct() {
        $this->SQL = MySQL::getInstance();
    }

    public function getLanguages() {
        return $this->SQL->fquery('
            SELECT id, code, name
            FROM languages'
        );
    }

    public function get($key, $langId = FALSE, $replaces = array()) {
        if(!$langId) {
            if(isset($_SESSION['user']['language_id'])) {
                $langId = $_SESSION['user']['language_id'];
            } else {
                //TODO: determine country by geo
                $langId = 1;
            }
        }
        $ret = $this->SQL->fetch_value('
            SELECT value
            FROM language_values
            WHERE language_id = %d
            AND `key` = "%s"
            LIMIT 1',
            $langId,
            $key
        );
        if($ret) {
            if($replaces) {
                return str_replace(array_map(array($this, 'addBraces'), array_keys($replaces)), array_values($replaces), $ret);
            } else {
                return $ret;
            }
        } else {
            return 'Not found: ' . $langId . '-' . $key;
        }
    }

    private function addBraces($val) {
        return '{' . $val . '}';
    }
}
?>
